<template>
  <div>
    <el-card shadow="never" class="sourcing-table-card">
      <el-row type="flex" justify="space-between" align="middle" slot="header">
        <h3>选择品类</h3>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="handleSubmit">保存并下一步</el-button>
      </el-row>
      <el-row type="flex" justify="space-between" align="middle" class="select-result">
        <div>已选品类：{{ selectedCategoryInfo.pathName }}</div>
        <div>
          <el-select
            v-model="recentUseInfo.categoryUuid"
            placeholder="最近使用的品类"
            @change="recentUseCategoryChange"
          >
            <el-option
              v-for="item in recentUseInfo.categoryList"
              :value="item.categoryUuid"
              :key="item.categoryUuid"
              :label="item.categoryPath"
            />
          </el-select>
        </div>
      </el-row>
      <el-divider class="divider" content-position="left">条件查询：</el-divider>
      <el-row type="flex" justify="space-between">
        <div>
          <el-input
            v-model="searchCategoryName"
            maxlength="20"
            placeholder="请输入要搜索的品类名称"
            @keyup.enter.native="getCategoryListByKey"
          >
            <el-button
              slot="append"
              type="primary"
              @click="getCategoryListByKey"
            >品类精确搜索</el-button>
          </el-input>
        </div>
        <el-form size="small" ref="searchFormData" :model="searchFormData" inline>
          <el-form-item prop="productName">
            <el-input
              type="text"
              v-model="searchFormData.productName"
              placeholder="输入商品名称可预测四级类"
              @keyup.enter.native="queryCategoryPredictions"
            />
          </el-form-item>
          <el-form-item prop="specDetailStr">
            <el-input
              type="text"
              v-model="searchFormData.specDetailStr"
              placeholder="输入规格预测更精准"
              @keyup.enter.native="queryCategoryPredictions"
            />
          </el-form-item>
          <el-form-item prop="brand">
            <el-input
              type="text"
              v-model="searchFormData.brand"
              placeholder="输入品牌预测更精准"
              @keyup.enter.native="queryCategoryPredictions"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryCategoryPredictions">品类智能搜索</el-button>
            <el-button style="marginLeft: 5px" @click="resetSearchForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="category-searchlist" v-show="categorySearchResults.length != 0">
        <div class="search-title">
          <span class="title">搜索结果如下：</span>
        </div>
        <el-radio-group v-model="selectedCategoryInfo.categoryUuid" @input="handleCheckSearchList" v-loading="searchLoading">
          <el-radio
            v-for="item in categorySearchResults"
            :label="item.categoryUuid"
            :key="item.categoryUuid"
          >
            {{ item.categoryPath }}&nbsp;&nbsp;{{ item.categoryNo }}
          </el-radio>
        </el-radio-group>
      </div>
      <el-divider class="divider" content-position="left">品类树选择：</el-divider>
      <el-row>
        <el-cascader-panel
          v-loading="treeInfo.loading"
          ref="categoryPannel"
          v-model="treeInfo.categoryValue"
          :props="treeInfo.props"
          @change="handleNodeChange"
        />
      </el-row>
    </el-card>
  </div>
</template>
<script>
import {
  getCategoryListByKeyService, // 搜索分类
  getLevelOneCategoryListService, // 查询一级分类
  getCategoryByParentUuidService, // 查询子级分类
  getCategoryPredictionsService, // 智能预测分类
  setCategoryPredictionsTrackService, // 智能预测分类埋点
} from '@api/public'
import {
  submitCategoryService, // 搜索分类
  queryRecentCategoryListService, // 最近使用品类
  queryCategoryLabelMsgService, // 获取品类的标签信息
} from '@api/commodity/commodityManage/addCommodity'
import { setAuthBtnId } from '@/utils/bizUtils';
import { uniqueCategoryUuidData } from '@/assets/js/utils';
import BasicInfo from '@/pages/commodity/commodityAccessManage/commodityAdd/basicInfo';
import { MEDICAL_EQUIPMENT_TYPE_LABELS } from './constants';

export default {
  components: {
    BasicInfo
  },
  data () {
    return {
      submitLoading: false,
      searchLoading: false,
      // 品类精确搜索条件
      searchCategoryName: '',
      // 智能搜索条件
      searchFormData: {
        brand: '',
        productName: '',
        specDetailStr: ''
      },
      // 最近使用品类信息
      recentUseInfo: {
        categoryUuid: '',
        categoryList: [],
      },
      // 已选品类信息
      selectedCategoryInfo: {
        pathName: '',
        categoryUuid: '',
      },
      treeInfo: {
        loading: false,
        categoryValue: '',
        props: {
          lazy: true
        },
        showPannel: false
      },
      productType: '01', // 商品类型：01-b2c实物商品;02-o2o实物商品;03-到店服务(预定)商品;04-到店服务（券）;05-上门服务商品;06-活动商品;
      categorySearchResults: [], // 条件查询列表
      needTracking: false // 是否需要埋点
    };
  },
  created () {
    this.initProps()
    this.queryRecentCategoryList();
  },
  methods: {
    // 通过名称查询品类
    async queryRecentCategoryList () {
      const res = await queryRecentCategoryListService({ oper: 'ljw' })
      if (res) {
        this.recentUseInfo.categoryList = uniqueCategoryUuidData(res.retData);
      }
    },
    // 通过名称查询品类
    async getCategoryListByKey () {
      if (!this.searchCategoryName) {
        return this.$message.warning('请输入需要搜索的品类名称!');
      }
      setAuthBtnId('关联-查询')
      const res = await getCategoryListByKeyService({ key: this.searchCategoryName }, state => {})
      if (res) {
        const { retData } = res
        if (retData?.length) {
          this.setNeedTrackValue(false, retData);
        } else {
          this.$message.error('未查询到对应品类')
        }
      }
    },
    // 品类预测
    async queryCategoryPredictions () {
      const res = await getCategoryPredictionsService(this.searchFormData)
      if (res) {
        const { retData } = res
        if (retData && retData.length) {
          const { categoryUuid, categoryPath } = retData[0]
          this.selectedCategoryInfo.categoryUuid = categoryUuid;
          this.selectedCategoryInfo.pathName = categoryPath;
          this.resetCheckedNodes()
          this.setNeedTrackValue(true, retData);

        } else {
          this.$message.error('未查询到对应品类')
        }
      }
    },
    // 品类预测埋点
    async setCategoryPredictionsTrack () {
      const params = [{
        ...this.searchFormData,
        categoryPredictionList: this.categorySearchResults,
        acceptFlag: 1
      }]
      const res = await setCategoryPredictionsTrackService(params)
      if (res) {}
    },
    // 获取一级目录
    async getLevelOneCategorys () {
      const res = await getLevelOneCategoryListService({})
      if (res) {
        return res.retData;
      }
    },
    // 获取一级目录
    async getLevelOtherCategoryList (parentUuid) {
      const res = await getCategoryByParentUuidService({ parentUuid, categoryType: this.productType })
      if (res) {
        return res.retData;
      }
    },
    // 初始化品类级联属性
    initProps () {
      this.treeInfo.showPannel = true;
      this.treeInfo.props.lazyLoad = (node, resolve) => {
        const { level, value } = node;
        if (level == 0) {
          this.treeInfo.loading = true;
          this.getLevelOneCategorys().then((res) => {
            this.treeInfo.loading = false;
            const nodes = res.map((item) => ({
              value: item.categoryUuid,
              label: item.categoryName,
              code: item.categoryNo,
              categoryPath: item.categoryPath,
              leaf: level >= 3,
              level: level + 1
            }));
            resolve(nodes);
          }).catch(() => {
            this.treeInfo.showPannel = false;
            this.treeInfo.loading = false;
            resolve(null);
          });
        } else {
          this.getLevelOtherCategoryList(value).then((res) => {
            const nodes = res.map((item) => ({
              value: item.categoryUuid,
              label: item.categoryName,
              code: item.categoryNo,
              categoryPath: item.categoryPath,
              leaf: level >= 3,
              level: level + 1
            }));
            resolve(nodes);
          });
        }
      };
    },
    // 选择末级分类
    handleNodeChange () {
      const selectNode = this.$refs['categoryPannel'].getCheckedNodes()[0];
      if (selectNode) {
        const { value, categoryPath } = selectNode.data;
        this.selectedCategoryInfo.categoryUuid = value;
        this.selectedCategoryInfo.pathName = categoryPath
        this.resetRecentUseSelect()
        this.setNeedTrackValue(false, []);
      }
    },
    // 勾选近期使用分类
    recentUseCategoryChange (value, type) {
      this.recentUseInfo.categoryList.forEach(item => {
        if (value === item.categoryUuid) {
          this.recentUseInfo.categoryUuid = item.categoryUuid;
          this.selectedCategoryInfo.categoryUuid = item.categoryUuid;
          this.selectedCategoryInfo.pathName = item.categoryPath;
        }
      });
      this.resetCheckedNodes();
      this.setNeedTrackValue(false, []);

    },
    // 选择查询列表项
    handleCheckSearchList (categoryUuid) {
      this.categorySearchResults.forEach(item => {
        if (item.categoryUuid === categoryUuid) {
          this.selectedCategoryInfo.pathName = item.categoryPath;
        }
      });
      this.resetCheckedNodes()
      this.resetRecentUseSelect()
    },
    // 重置智能搜索条件
    resetSearchForm () {
      this.$refs['searchFormData'].resetFields();
    },
    // 清空品类树选项
    resetCheckedNodes () {
      if (this.$refs['categoryPannel']) {
        this.$refs['categoryPannel'].clearCheckedNodes();
      }
    },
    // 清空近期使用勾选项
    resetRecentUseSelect () {
      this.recentUseInfo.categoryUuid = ''
    },
    // 选完分类进入下一步操作
    async handleSubmit () {
      const { categoryUuid } = this.selectedCategoryInfo
      if (categoryUuid === 'systemUuid' || !categoryUuid) {
        return this.$message.error('请先选择品类');
      }
      this.getCategoryLabelMsg()
    },
    // 提交品类信息
    async submitCategoryInfo () {
      const { categoryUuid } = this.selectedCategoryInfo
      const res = await submitCategoryService({ categoryUuid }, state => { this.submitLoading = state })
      if (res) {
        if (this.needTracking && this.categorySearchResults.length === 1) {
          this.setCategoryPredictionsTrack()
        }
        this.$router.push({ name: 'commodityBasicInfo', query: { categoryUuid } })
      }
    },
    // 获取品类的标签信息
    async getCategoryLabelMsg () {
      const data = { categoryUuid: this.selectedCategoryInfo?.categoryUuid }
      const loadingFn = state => { this.submitLoading = state }
      const res = await queryCategoryLabelMsgService(data, loadingFn)
      if (!res?.retData?.medicalEquipmentType) return this.submitCategoryInfo()
      this.alertSpecialCategoryWarning(res?.retData)
    },
    // 特殊品类提醒
    alertSpecialCategoryWarning (retData) {
      const h = this.$createElement
      this.$msgbox({
        title: '特殊品类提醒',
        showClose: false,
        message: h('div', null, [
          h('div', null, `您选择的品类为${MEDICAL_EQUIPMENT_TYPE_LABELS[retData?.medicalEquipmentType]  ?? ''}`),
          h('h6', null, '品类标签说明：'),
          h('div', null, retData?.medicalEquipmentDescription)
        ])
      }).then(() => {
        this.submitCategoryInfo()
      }).catch(() => {})
    },
    // 设置是否需要埋点
    setNeedTrackValue (val, searchResult = []) {
      this.needTracking = val;
      this.categorySearchResults = searchResult;
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .el-cascader-menu {
  width: 25%;
}
.category-searchlist {
  .el-radio-group {
    border: 1px solid #ebeef5;
    padding-left: 5px;
    width: 100%;
    max-height: 200px;
    overflow-y: auto;
    label {
      display: block;
      line-height: 27px;
      &:first-child {
        margin-top: 10px;
      }
      &:last-child {
        margin-bottom: 10px;
      }
    }
  }
  .search-title {
    display: flex;
    background: #fbfafa;
    justify-items: center;
    align-items: center;
    padding: 0 0 0 10px;
    .title {
      flex: 1;
    }
  }
}
.select-result {
  width: 100%;
  height: 45px;
  background: #ecf5ff;
  margin-bottom: 10px;
  .el-select {
    width: 400px;
  }
}
/deep/ .el-input-group__append, .el-input-group__prepend {
  background-color: #409eff;
  color: #fff;
  vertical-align: middle;
  display: table-cell;
  position: relative;
  border: 1px solid #409eff;
  border-radius: 4px;
  padding: 0 20px;
  width: 1px;
  white-space: nowrap;
}
</style>
